import 'package:json_annotation/json_annotation.dart';

part 'comment.g.dart';

@JsonSerializable()
class Comment {
  final String id;
  @JsonKey(name: 'post_id', fromJson: _stringFromJson)
  final String postId; // 确保为String类型
  @JsonKey(name: 'user_id', fromJson: _stringFromJson)
  final String userId;
  final String content;
  @JsonKey(name: 'create_time')
  final int createTime;

  Comment({
    required this.id,
    required this.postId,
    required this.userId,
    required this.content,
    required this.createTime,
  });

  // 自定义fromJson转换器（处理数字转字符串）
  static String _stringFromJson(dynamic json) {
    return json?.toString() ?? '';
  }

  // 覆盖自动生成的fromJson方法
  factory Comment.fromJson(Map<String, dynamic> json) {
    return Comment(
      id: json['id']?.toString() ?? '',
      postId: _stringFromJson(json['post_id']),
      userId: _stringFromJson(json['user_id']),
      content: json['content'] as String? ?? '',
      createTime: (json['create_time'] as num?)?.toInt() ?? 0,
    );
  }

  // 保持自动生成的toJson
  Map<String, dynamic> toJson() => _$CommentToJson(this);

  DateTime get createdAt => DateTime.fromMillisecondsSinceEpoch(createTime * 1000);
}